package com.homestead.service.impl;

import com.homestead.service.CouponRedisService;
import com.homestead.utils.LuaUtil;
import org.redisson.api.RScript;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.LongCodec;
import org.redisson.client.codec.StringCodec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * @author yhb
 * @date 2021-05-25 8:35
 */
@Service
public class CouponRedisServiceImpl implements CouponRedisService {
    @Autowired
    private RedissonClient redissonClient;

    /**
     * 尝试从redis中获取一个优惠券码
     * @param keyName redis key
     * @return key不存在返回null key存在但是没有数据了返回-1 成功返回一个string数据
     */
    @Override
    public List<String> tryToAcquireCouponCodesFromCache(String keyName, int amount) {
        return redissonClient.getScript(StringCodec.INSTANCE).evalSha(RScript.Mode.READ_WRITE, LuaUtil.getSha("getCouponCode.lua"), RScript.ReturnType.MULTI, Collections.singletonList(keyName), amount);
    }

    @Override
    public List<Long> tryToAcquireCouponIdsFromCache(String keyName, int amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("amount illegal, amount=" + amount);
        }
        return redissonClient.getScript(LongCodec.INSTANCE).evalSha(RScript.Mode.READ_WRITE, LuaUtil.getSha("getCouponIds.lua"), RScript.ReturnType.MULTI, Collections.singletonList(keyName), amount);
    }
}
